package consulinit

import (
	"common/config"
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
)

// ServiceRegistration 服务注册参数
type ServiceRegistration struct {
	Name    string
	Address string
	Port    int
	Tags    []string
	ID      string // 可选，如果为空则自动生成
}

// RegisterService 注册服务到Consul
func RegisterService(reg ServiceRegistration) {
	if reg.ID == "" {
		reg.ID = uuid.NewString()
	}

	registration := &api.AgentServiceRegistration{
		ID:      reg.ID,
		Name:    reg.Name,
		Address: reg.Address,
		Port:    reg.Port,
		Tags:    reg.Tags,
	}

	file := `Service==` + reg.Name

	filter, err := config.Consul.Agent().ServicesWithFilter(file)
	if err != nil {
		zap.S().Error(err.Error())
		return
	}

	if len(filter) == 0 {
		err = config.Consul.Agent().ServiceRegister(registration)
		if err != nil {
			return
		} else {
			zap.S().Info("服务注册成功")
		}
	} else {
		zap.S().Info("服务已经注册")
	}
}
